<template>
    <div>
        <h2>发布图片</h2>
        <div class="upload">
            <div class="upload-image">
                <el-upload
                    action="action"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    list-type="picture-card"
                    :auto-upload="true"
                    :limit="1"
                    :before-upload="beforeUpload"
                    :http-request="uploadPhoto"
                    :on-exceed="handleExceed"
                    ref="pictureUpload"
                >
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{ file }">
                        <img
                            class="el-upload-list__item-thumbnail"
                            :src="file.url"
                            alt=""
                        />
                        <span class="el-upload-list__item-actions">
                            <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)"
                            >
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleRemoveThis(file)"
                            >
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <div slot="tip" class="el-upload__tip">只能上传1张图片</div>
            </div>
            <div class="upload-form">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="100px"
                    class="ruleForm"
                >
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="ruleForm.title"></el-input>
                    </el-form-item>
                    <el-form-item
                        label="描述"
                        prop="information"
                        style="height: 100%"
                    >
                        <el-input
                            type="textarea"
                            class="textarea"
                            resize="none"
                            :rows="10"
                            v-model="ruleForm.information"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="分类" prop="categoryId">
                        <div class="block">
                            <el-cascader
                                v-model="ruleForm.categoryId"
                                :options="options"
                                @change="handleChange"
                            ></el-cascader>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            @click="submitForm('ruleForm')"
                            >立即发布</el-button
                        >
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import imageApi from '../request/imageApi';
export default {
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            ruleForm: {
                title: '',
                information: '',
                categoryId: '',
                link: '',
            },
            rules: {
                title: [
                    {
                        required: true,
                        message: '请输入图片名称',
                        trigger: 'blur',
                    },
                    {
                        min: 2,
                        max: 8,
                        message: '长度在 2 到 8 个字符',
                        trigger: 'blur',
                    },
                ],
                information: [
                    {
                        required: true,
                        message: '请输入图片描述',
                        trigger: 'blur',
                    },
                ],
                categoryId: [
                    {
                        required: true,
                        message: '请选择图片分类',
                        trigger: 'blur',
                    },
                ],
            },
            options: [],
        };
    },
    created() {
        this.getCategory();
    },
    methods: {
        handleRemove(file) {
            file.slice;
        },
        handleRemoveThis(file) {
            this.$refs.pictureUpload.handleRemove(file);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            console.log(file.url);
            this.dialogVisible = true;
        },
        handleSuccess(res, file) {
            console.log(1111);
            console.log(res);
        },
        handleError(res) {
            console.log(11);
            console.log(res);
        },
        submitForm(formName) {
            console.log(this.ruleForm.link);
            if (this.ruleForm.link == '') {
                this.$message.error('请上传图片');
                return;
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    imageApi.insertPhoto(this.ruleForm).then((res) => {
                        if (res.code === 200) {
                            this.$message.success('发布成功');
                            this.$router.push('/home');
                        } else {
                            this.$message.error('发布失败');
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        beforeUpload(file) {
            this.openFullScreen();
        },
        uploadPhoto(param) {
            // https://www.hualigs.cn/api/upload?apiType=huluxia&token=6e55474d55ecf6fde56f16e9d242181f
            const formData = new FormData();
            formData.append('image', param.file); // 传入bpmn文件
            formData.append('apiType', 'huluxia');
            formData.append('token', '6e55474d55ecf6fde56f16e9d242181f');
            axios
                .post('https://www.hualigs.cn/api/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                })
                .then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            message: '上传成功',
                            type: 'success',
                        });
                    } else {
                        this.$message({
                            message: '该图片不能上传，请换张图片',
                            type: 'error',
                        });
                    }
                    this.closeFullScreen(this.openFullScreen());
                    console.log('图床地址');
                    console.log(res.data.data.url.huluxia);
                    this.ruleForm.link = res.data.data.url.huluxia;
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${
                    files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },
        openFullScreen() {
            const loading = this.$loading({
                lock: true,
                text: '图片上传中，请稍等',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            setTimeout(() => {
                console.log(loading.close());
            }, 30000);
            return loading;
        },
        closeFullScreen(loading) {
            loading.close();
        },
        handleChange(value) {
            this.ruleForm.categoryId = value[value.length - 1];
            console.log(this.ruleForm);
        },
        getCategory() {
            let name = '探索';
            imageApi.getImgBox(name).then((res) => {
                res.data.map((item) => {
                    this.options.push({
                        value: item.categoryId,
                        label: item.name,
                    });
                });
            });
        },
    },
};
</script>
<style scoped>
body {
    background-color: #f7f8f9;
    width: 100%;
    height: 100%;
}
h2 {
    color: #4b4b4b;
}

.ruleForm {
    height: 100%;
}
::v-deep .el-upload--picture-card {
    width: 250px;
    height: 250px;
    line-height: 250px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 250px;
    height: 250px;
}
.upload-image {
    float: left;
    margin-left: 5px;

    padding: 5px;
    width: 65%;

    border-radius: 5px;
    background-color: #e1e1e1;
}
.upload-image > div {
    height: 100%;
    width: 100%;

    margin-left: 5px;
    margin-top: 5px;
}
.main > div {
    height: 80vh;
}
.upload-form {
    float: right;
    margin-right: 5px;
    padding-top: 20px;
    padding-right: 20px;
    width: 30%;
    background-color: #e1e1e1;
    border-radius: 5px;
}
</style>